package com.yxy.controller.service;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.yxy.common.ServerResponse;
import com.yxy.util.ValidateCode;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;


@Controller
@RequestMapping("/code/")
public class CodeController {

	/**
	 * 生成图片验证码
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	@RequestMapping(value = "getcode", method = RequestMethod.GET)
	public void validateCode(HttpServletRequest request, HttpServletResponse response) throws IOException {
		response.setContentType("image/jpeg");
        // 禁止图像缓存
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);

        HttpSession session = request.getSession();

        ValidateCode vCode = new ValidateCode(116, 36, 4, 100);
        session.setAttribute("code", vCode.getCode());
        vCode.write(response.getOutputStream());
	}
	@RequestMapping(value = "checkCode.do", method = RequestMethod.GET)
	@ResponseBody
	public ServerResponse<String> checkCode(String code, HttpServletRequest request, HttpSession session) throws IOException {
		if(code==null || code==""){
			return ServerResponse.createByErrorMessage("验证码未填写");
		}
		String sessionCode = session.getAttribute("code").toString();
		if(sessionCode!=null && !sessionCode.equals(code.toUpperCase())){
			return ServerResponse.createByErrorMessage("验证码错误");
		}
		return ServerResponse.createBySuccessMessage("验证码正确");
	}
}
